<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="名称" width="120" sortable>
			</el-table-column>
      <el-table-column prop="sn" label="部门名称" width="100" sortable>
      </el-table-column>
      <el-table-column prop="dirPath" label="上级部门层级id" width="150" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="120" sortable>
        <template scope="scope">
          <span style="color: green" v-if="scope.row.state==0">正常</span>
          <span style="color: red" v-else-if="scope.row.state==-1" >禁用</span>
          <span style="color: gray" v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="employee.username" label="部门管理员" width="150" sortable>
      </el-table-column>
			<el-table-column prop="parent.name" label="上级部门" min-width="180" sortable>
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--分页-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next"
                         @current-change="handleCurrentChange"
                        :current-page="currentPage"
                         :page-size="pageSize"
                         :total="total"
                          style="float:right;">
			</el-pagination>
		</el-col>

    <!--编辑界面-->
    <el-dialog :title="myTitle" :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="编号" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="editForm.state">
            <el-radio class="radio" :label="0">正常</el-radio>
            <el-radio class="radio" :label="-1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="管理员">
          <!--<el-input v-model="editForm.employee"></el-input>-->
          <el-select v-model="editForm.employee" value-key="id" placeholder="请选择">
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <!--<el-input v-model="editForm.parent"></el-input>-->
          <!--
            value  这是格式默认的当不一样时需要自己给他定义
            label  这是格式默认的当不一样时需要自己给他定义
          -->
          <el-cascader
              :options="deptTree"
              :props="{
                checkStrictly: true,
                value:'id',
                label:'name'
              }"
              clearable></el-cascader>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>

</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment } from '../../api/api';

	export default {
		data() {
      return {
        myTitle: "",
        //管理员
        employees:[],
        //无限极树
        deptTree:[],
        filters: {
          //关键字查询
          keyword: ''
        },
        departments: [],
        /*绑定分页条*/
        total: 0,
        currentPage: 1,
        pageSize: 6,
        listLoading: false,
        sels: [],//列表选中列

        editFormVisible: false,//编辑界面是否显示
        editLoading: false,
        editFormRules: {
          name: [
            {required: true, message: '请输入编号', trigger: 'blur'}
          ]
        },
        //编辑界面数据
        editForm: {
          id: null,
          name: "",
          sn: "",
          state: 0,
          manger: null,
          parent: null,
          dirPath: ""
        }
      }
    },
      methods: {
        //状态显示转换
        search: function (row, column) {
          return row.state == 0 ? '正常' : row.state == -1 ? '禁用' : '未知';
        },
        searchval() {//高级查询完成后返回第一页
          this.currentPage = 1;
          this.getDepartments();
        },
        handleCurrentChange(val) {
          //对页数重新赋值调用方法
          this.currentPage = val;
          this.getDepartments();
        },
        //获取部门列表
        getDepartments() {
          let para = {
            /*显示第几页*/
            currentPage: this.currentPage,
            /*每页显示的数据条数*/
            pageSize: this.pageSize,
            /*把关键字传给后端*/
            keyword: this.filters.keyword
          };
          /*开启盲等就是加载转圈显示加载的意思*/
          this.listLoading = true;
          this.$http.post("/dept", para)
              .then(result => {
                /*当调取后端参数完毕时关闭盲等显示数据*/
                this.listLoading = false;
                //相当于放回的pageList
                result = result.data;
                //渲染列表
                this.departments = result.rows;
                this.total = result.total;
              })
              .catch(result => {
                console.log(result);
                this.message({
                  message: '对不起，服务器正在维护请稍后重试',
                  type: 'error'
                })
              })
        },

        //删除
        handleDel: function (index, row) {
          this.$confirm('确认删除该记录吗?', '温馨提示', {
            type: 'warning'
          }).then(() => {
            //开启列表加载忙等
            this.listLoading = true;
            this.$http.delete("/dept/" + row.id)
                .then(result => {
                  //当执行删除后关闭盲等，不然会一致转圈
                  this.listLoading = false;
                  result = result.data;//AjaxResult
                  if (!result.success) {
                    this.$message({
                      //报错后把后端代码写的异常提示打印出来
                      message: result.message,
                      type: 'error'
                    });
                  }
                  //删除数据成功后返回第一页
                  this.currentPage = 1;
                  //调用方法刷新页面
                  this.getDepartments();
                })
                .catch(result => {
                  console.log(result);
                  this.$message({
                    message: '系统繁忙，稍后重试！',
                    type: 'error'
                  });
                })
          }).catch(() => {//取消

          });
        },

        //显示编辑界面
        handleEdit: function (index, row) {
          //回显无限极树
          this.getDeptTree();
          this.myTitle = "编辑",
              //绑定模态框
              this.editFormVisible = true;
          //克隆回显数据,如果直接row就是双向绑定不用点击确定就直接修改
          this.editForm = Object.assign({}, row);
        },
        //显示新增界面
        handleAdd: function () {
          //回显无限极树
          this.getDeptTree();
          this.myTitle = "新增",
              this.editFormVisible = true;
          this.editForm = {
            id: null,
            name: "",
            sn: "",
            state: 0,
            manger: null,
            parent: null,
            dirPath: ""
          };
        },
        //编辑
        editSubmit: function () {
          this.$refs.editForm.validate((valid) => {
            if (valid) {
              this.$confirm('确认提交吗？', '提示', {}).then(() => {
                this.editLoading = true;
                //NProgress.start();
                let para = Object.assign({}, this.editForm);
                this.$http.put("/dept", para)
                    .then(result => {
                      //关闭盲等
                      this.editLoading = false;
                      result = result.data;//AjaxResult
                      if (!result.success) {
                        this.$message({
                          //报错后把后端代码写的异常提示打印出来
                          message: result.message,
                          type: 'error'
                        });
                      }else{
                        this.$message({
                          //报错后把后端代码写的异常提示打印出来
                          message: result.message,
                          type: 'error'
                        });
                        //关闭模态框
                        this.editFormVisible = false;
                      }
                      //删除数据成功后返回第一页
                      this.currentPage = 1;
                      //调用方法刷新页面
                      this.getDepartments();
                    })
                    .catch(result => {
                      console.log(result);
                      this.$message({
                        message: '系统繁忙，稍后重试！',
                        type: 'error'
                      });
                    })
              });
            }
          });
        },
        //新增
        addSubmit: function () {
          this.$refs.editForm.validate((valid) => {
            if (valid) {
              this.$confirm('确认提交吗？', '提示', {}).then(() => {
                this.addLoading = true;
                //NProgress.start();
                let para = Object.assign({}, this.editForm);
                para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
                addDepartment(para).then((res) => {
                  this.addLoading = false;
                  //NProgress.done();
                  this.$message({
                    message: '提交成功',
                    type: 'success'
                  });
                  this.$refs['editForm'].resetFields();
                  this.editFormVisible = false;
                  this.getDepartments();
                });
              });
            }
          });
        },
        selsChange: function (sels) {
          this.sels = sels;
        },
        //批量删除
        batchRemove: function () {
          //数组id
          var ids = this.sels.map(item => item.id);
          this.$confirm('确认删除选中记录吗？', '提示', {
            type: 'warning'
          }).then(() => {
            this.$http.patch("/dept", ids)
                .then(result => {
                  result = result.data;//AjaxResult
                  if (!result.success) {
                    this.$message({
                      //报错后把后端代码写的异常提示打印出来
                      message: result.message,
                      type: 'error'
                    });
                  }
                  //删除数据成功后返回第一页
                  this.currentPage = 1;
                  //调用方法刷新页面
                  this.getDepartments();
                })
                .catch(result => {
                  console.log(result);
                  this.$message({
                    message: '系统繁忙，稍后重试！',
                    type: 'error'
                  });
                })
            //NProgress.start();
            let para = {ids: ids};
            batchRemoveDepartment(para).then((res) => {
              this.listLoading = false;
              //NProgress.done();
              this.$message({
                message: '删除成功',
                type: 'success'
              });
              this.getDepartments();
            });
          }).catch(() => {

          });
        },
        //管理员数据回显
        getEmployees(){
          this.$http.get("/employee")
          .then(result=>{
            this.employees = result.data;
          })
        },
        getDeptTree(){
          this.$http.get("/dept/tree")
          .then(result=>{
            //获取第一层级
            this.deptTree = result.data;
          })
        }
      },
      mounted() {
		     //列表查询
        this.getDepartments();
        //管理员数据回显
        this.getEmployees();
      }
    }


</script>

<style scoped>

</style>
